print("Loading server.py...")

from flask import Flask, jsonify
from flask_cors import CORS
import json
from pathlib import Path
from flask import request
import os
import logging

logging.basicConfig(
    filename="explorer.log",
    level=logging.INFO
)

logging.info("Explorer started")

try:
    # Running as a package (python -m explorer.server)
    from .helpers import get_workspace
    from .context import ExplorerContext
except ImportError:
    # Running directly (python server.py)
    from helpers import get_workspace
    from context import ExplorerContext

print('Helper Imported')

ctx = ExplorerContext()

print("ExplorerContext created.")

app = Flask(__name__)

CORS(app)

BASE = Path(__file__).parent

@app.get("/")
def index():
    return "Explorer running"

@app.get("/health")
def health():
    return jsonify({
        "ok": True,
        "service": "Project Awareness Explorer",
        "version": "0.2"
    })

@app.get("/api/workspaces")
def api_workspaces():
    with open(BASE / "workspaces.json", "r", encoding="utf-8") as f:
        return jsonify({
            "ok": True,
            "workspaces": json.load(f)
        })
    
@app.get("/api/tree")
def api_tree():

    print("TREE ENDPOINT HIT")

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing workspace alias"
        }), 400

    workspace = get_workspace(alias)

    if workspace is None:
        return jsonify({
            "ok": False,
            "error": "Workspace not found"
        })

    root = Path(workspace["root"])

    if not root.exists():
        return jsonify({
            "ok": False,
            "error": "Workspace path does not exist",
            "root": str(root)
        })

    folders = []

    for item in sorted(root.iterdir()):

        if item.is_dir():

            folders.append({
                "name": item.name,
                "type": "folder"
            })

    return jsonify({
        "ok": True,
        "workspace": workspace["alias"],
        "root": str(root),
        "folders": folders
    })


@app.get("/api/search")
def api_search():

    print("SEARCH ENDPOINT HIT")

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing workspace alias"
        }), 400

    alias = alias.lower()

    
    q = request.args.get("q")
    
    if not q:
        return jsonify({
            "ok": False,
            "error": "Missing query"
        }), 400

    alias = alias.lower()

    with open(BASE / "workspaces.json", "r", encoding="utf-8") as f:
        workspaces = json.load(f)

    workspace = None

    for item in workspaces:
        if item["alias"].lower() == alias:
            workspace = item
            break
            
    if workspace is None:
        return jsonify({
            "ok": False,
            "error": "Workspace not found"
        })

    root = Path(workspace["root"])

    if not root.exists():
        return jsonify({
            "ok": False,
            "error": "Workspace path does not exist",
            "root": str(root)
        })
    
    root = Path(workspace["root"])

    results = []

    q = q.lower()

    for path in root.rglob("*"):

        if not path.is_file():
            continue

        if q in path.name.lower():
            results.append(
                str(path.relative_to(root))
            )

    return jsonify({
    "ok": True,
    "results": results
})

@app.get("/api/workspace")
def api_workspace():

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing workspace alias"
        }), 400

    workspace = get_workspace(alias)

    if workspace is None:
        return jsonify({
            "ok": False,
            "error": "Workspace not found"
        })

    return jsonify({
        "ok": True,
        "workspace": workspace
    })

@app.get("/api/project")
def api_project():

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing project alias"
        }), 400

    alias = alias.lower()

    file = BASE.parent / "gateway" / "data" / "projects" / f"{alias}.json"

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "Project not found"
        })

    with open(file, "r", encoding="utf-8") as f:
        data = json.load(f)

    return jsonify({
        "ok": True,
        "project": data
    })

@app.get("/api/manifest")
def api_manifest():

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing project alias"
        }), 400

    alias = alias.lower()

    file = (
    BASE.parent
    / "gateway"
    / "data"
    / "manifests"
    / f"{alias}.json"
)

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "Manifest not found"
        })

    with open(file, "r", encoding="utf-8") as f:
        manifest = json.load(f)

    return jsonify({
        "ok": True,
        "manifest": manifest
    })

@app.get("/api/module")
def api_module():

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing module alias"
        }), 400

    file = (
        BASE.parent
        / "gateway"
        / "data"
        / "modules"
        / f"{alias}.json"
    )

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "Module not found"
        }), 404

    with open(file, "r", encoding="utf-8") as f:
        module = json.load(f)

    return jsonify({
        "ok": True,
        "module": module
    })

# Note: 
# This intentionally mirrors the current PHP behavior by returning 
# the same module metadata. If, in a later refactor, moduleInfo evolves 
# into a distinct concept, we can separate the endpoints without changing 
# the Gateway contract.
@app.get("/api/moduleInfo")
def api_module_info():

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing module alias"
        }), 400

    file = (
        BASE.parent
        / "gateway"
        / "data"
        / "modules"
        / f"{alias}.json"
    )

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "Module not found"
        }), 404

    with open(file, "r", encoding="utf-8") as f:
        module = json.load(f)

    return jsonify({
        "ok": True,
        "module": module
    })

@app.get("/api/registry")
def api_registry():

    file = (
        BASE.parent
        / "gateway"
        / "data"
        / "projects"
        / "gateway.json"
    )

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "Registry not found"
        }), 404

    with open(file, "r", encoding="utf-8") as f:
        registry = json.load(f)

    return jsonify({
        "ok": True,
        "registry": registry
    })

@app.get("/api/gatewayInfo")
def api_gateway_info():

    file = (
        BASE.parent
        / "gateway"
        / "data"
        / "projects"
        / "gateway.json"
    )

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "Gateway information not found"
        }), 404

    with open(file, "r", encoding="utf-8") as f:
        gateway = json.load(f)

    return jsonify({
        "ok": True,
        "gateway": gateway
    })

@app.get("/api/health")
def api_health():

    return jsonify({
        "ok": True,
        "status": "healthy"
    })

@app.get("/api/file")
def api_file():

    path = request.args.get("path")

    if not path:
        return jsonify({
            "ok": False,
            "error": "Missing path"
        }), 400

    file = BASE.parent / path

    if not file.exists():
        return jsonify({
            "ok": False,
            "error": "File not found"
        }), 404

    if not file.is_file():
        return jsonify({
            "ok": False,
            "error": "Not a file"
        }), 400

    try:
        with open(file, "r", encoding="utf-8") as f:
            text = f.read()

        return jsonify({
            "ok": True,
            "path": path,
            "content": text
        })

    except Exception as e:
        return jsonify({
            "ok": False,
            "error": str(e)
        }), 500

@app.get("/api/context")
def api_context():

    return jsonify({
        "ok": True,
        "builder": "Session 20 Gateway",
        "explorer_context": True,
        "gateway_url": ctx.gateway.base_url,
        "workspace": ctx.workspace_alias,
        "reports_loaded": len(ctx.reports)
    })

@app.get("/api/context/status")
def api_context_status():

    return jsonify({
        "ok": True,
        "context": {
            "workspace": ctx.workspace_alias,
            "project_root": getattr(ctx, "project_root", None),
            "explorer_root": ctx.explorer_root,
            "reports_loaded": len(ctx.reports)
        },
        "services": {
            "gateway": ctx.gateway is not None,
            "workspace": ctx.workspace is not None,
            "project": ctx.project is not None,
            "search": ctx.search is not None,
            "discovery": ctx.discovery is not None
        }
    })

print("REGISTERING WORKSPACE ROUTE")
@app.get("/api/context/workspace")
def api_context_workspace():

    if ctx.workspace_alias is None:
        return jsonify({
            "ok": True,
            "active": None,
            "workspace": None
        })

    workspace = ctx.workspace.get(ctx.workspace_alias)

    return jsonify({
        "ok": True,
        "active": ctx.workspace_alias,
        "workspace": workspace
    })

@app.get("/api/context/useWorkspace")
def api_context_use_workspace():

    alias = request.args.get("alias")

    if not alias:
        return jsonify({
            "ok": False,
            "error": "Missing workspace alias"
        }), 400

    try:

        workspace = ctx.use_workspace(alias)

        return jsonify({
            "ok": True,
            "active": alias,
            "workspace": workspace
        })

    except Exception as ex:

        return jsonify({
            "ok": False,
            "error": str(ex)
        }), 500
    
@app.get("/api/context/discovery")
def api_context_discovery():

    return jsonify({
        "ok": True,
        "reports_loaded": len(ctx.reports),
        "reports": list(ctx.reports.keys())
        if isinstance(ctx.reports, dict)
        else ctx.reports
    })

@app.get("/api/reality")
def api_reality():
    return jsonify({
        "ok": True,
        "protocol": 1,

        "identity": {
            "name": "Manyfest Explorer",
            "builder": "Session Gateway"
        },

        "status": {
            "explorer": True,
            "context": True
        },

        "context": {
            "workspace": ctx.workspace_alias,
            "reports_loaded": len(ctx.reports)
        },

        "capabilities": [
            "health",
            "registry",
            "workspaces",
            "context"
        ],

        "next": [
            "/api/workspaces",
            "/api/registry"
        ]
    })

if __name__ == "__main__":

    print(app.url_map)

    print("Explorer ready.")
    
    app.run(
        host="0.0.0.0",
        port=5050,
        debug=False
    )
    